﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
using System.Net;
using ERP.Model.Base;
using ERP.BLL.Base;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using ERP.DAL;
using Microsoft.AspNetCore.Hosting;

namespace ERP.Controllers
{
    public class BasicsController : Controller
    {
        /// <summary>
        /// 控制器返回
        /// </summary>
        protected ActionResult ReturnView = null;

        /// <summary>
        /// 控制器返回Json集
        /// </summary>
        protected Base.Json.JsonObj json = new Base.Json.JsonObj();

        #region URL参数获取
        /// <summary>
        /// GET 获取参数，做特殊符号处理
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        [NonAction]
        protected string Get(string param)
        {
            return HttpContext.Request.Query[param].ToString();
        }


        /// <summary>
        /// POST 获取参数
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        [NonAction]
        protected string Post(string param)
        {
            string Rstr = "";
            if (HttpContext.Request != null)
            {
                try
                {
                    Rstr = HttpContext.Request.Form[param] + "";
                }
                catch { }
            }
            return Rstr;
        }
        #endregion
        #region 获取登录信息

        protected T FromJSON<T>(string jsonString)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString);
        }


        protected List<T> JsonToList<T>(string jsonString)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(jsonString);
        }

        #region 登录账户
        /// <summary>
        /// 获取账户ID
        /// </summary>
        protected int BaseAccountID
        {
            get
            {
                return int.Parse(HttpUtility.UrlDecode(GetCookies("TBA_DID")));
            }
        }

        /// <summary>
        /// 获取账户名称
        /// </summary>
        protected string BaseAccountName
        {
            get
            {
                return HttpUtility.UrlDecode(GetCookies("TBA_NAME"));
            }
        }

        /// <summary>
        /// 获取账户手机号码
        /// </summary>
        protected string BaseAccountIphone
        {
            get
            {
                return HttpUtility.UrlDecode(GetCookies("TBA_IPHONE"));
            }
        }

        /// <summary>
        /// 获取账户邮箱
        /// </summary>
        protected string BaseAccountEMail
        {
            get
            {
                return HttpUtility.UrlDecode(GetCookies("TBA_EMAIL"));
            }
        }

        /// <summary>
        /// 获取账户头像路径
        /// </summary>
        protected string BaseAccountHPhoto
        {
            get
            {
                return HttpUtility.UrlDecode(GetCookies("TBA_HPHOTO"));
            }
        }
        #endregion

        #region 用户（账号在每个企业内用户是分开，且唯一）

        /// <summary>
        /// 获取企业ID
        /// </summary>
        protected int BaseUserEnterpriseID
        {
            get
            {
                return int.Parse(HttpUtility.UrlDecode(GetCookies("TBE_DID")));
            }
        }

        /// <summary>
        /// 获取企业名称
        /// </summary>
        protected string BaseUserEnterpriseName
        {
            get
            {
                return HttpUtility.UrlDecode(GetCookies("TBE_NAME"));
            }
        }

        /// <summary>
        /// 获取用户ID
        /// </summary>
        protected decimal BaseUserID
        {
            get
            {
                return decimal.Parse(HttpUtility.UrlDecode(GetCookies("TBU_DID")));
            }
        }

        #endregion

        #endregion


        protected void SetCookies(string key, string value)
        {
            HttpContext.Response.Cookies.Append(key, value, new Microsoft.AspNetCore.Http.CookieOptions
            {
                Expires = DateTime.Now.AddDays(3)
            });
        }

        protected string GetCookies(string key)
        {
            string value = "";
            HttpContext.Request.Cookies.TryGetValue(key, out value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }

        protected void DeleteCookies(string key)
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        #region 赋值对象       
        /// <summary>
        /// 自动赋值对象
        /// </summary>
        /// <param name="uobj">对象</param>
        protected void Base_SetObj(object uobj)
        {
            Type t = uobj.GetType();

            #region POST
            try
            {
                foreach (var item in HttpContext.Request.Form)
                {
                    string ID = item.Key;
                    string value = item.Value;
                    if (ContainProperty(uobj, ID))
                    {
                        try
                        {
                            var property = t.GetProperty(ID);
                            property.SetValue(uobj, Convert.ChangeType(value, property.PropertyType), null);
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
            catch { }
            #endregion

            #region GET
            foreach (var item in HttpContext.Request.Query)
            {
                string ID = item.Key;
                string value = item.Value;
                if (ContainProperty(uobj, ID))
                {
                    try
                    {
                        var property = t.GetProperty(ID);
                        property.SetValue(uobj, Convert.ChangeType(value, property.PropertyType), null);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            #endregion

        }

        /// <summary>
        /// 利用反射来判断对象是否包含某个属性
        /// </summary>
        /// <param name="instance">object</param>
        /// <param name="propertyName">需要判断的属性</param>
        /// <returns>是否包含</returns>
        public bool ContainProperty(object instance, string propertyName)
        {
            if (instance != null && !string.IsNullOrEmpty(propertyName))
            {
                object ss = instance.GetType();
                PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
                return (_findedPropertyInfo != null);
            }
            return false;
        }
        #endregion
        #region 字符串处理

        #region MD5加密
        /// <summary>
        /// 32位大写MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected string Md5Hash(string input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString().ToUpper();
        }
        #endregion

        #endregion
        #region 操作日志
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="order">操作指令</param>
        /// <param name="model">操作模块</param>
        /// <param name="log">操作日志</param>
        protected void InLog(OrderEnum order, ModelEnum model, string log)
        {

        }
        /// <summary>
        /// 操作指令 枚举类型定义
        /// </summary>
        public enum OrderEnum
        {
            Add = 0,       //新增
            Update = 1,    //修改
            Delete = 2,    //删除
            Query = 3      //查询
        }
        /// <summary>
        /// 操作模块 枚举类型定义
        /// </summary>
        public enum ModelEnum
        {
            Base = 0,         //基础信息
            Order = 1,        //订单信息
            BackOrder = 2     //退货信息
        }
        #endregion
        #region Mail发送验证码
        /// <summary>
        /// Mail发送验证码
        /// </summary>
        /// <param name="ToMail">接收人邮箱</param>
        /// <returns>返回值非空时异常</returns>
        protected string SendMail(string ToMail)
        {
            string RetMsg = "";
            string FromName = "627423775@qq.com";
            try
            {
                //生成四位验证码
                Random rd = new Random();
                string RanNum = rd.Next(1, 10).ToString() + rd.Next(1, 10).ToString()
                    + rd.Next(1, 10).ToString() + rd.Next(1, 10).ToString();

                MailMessage myMail = new MailMessage(); //创建邮件实例对象
                myMail.From = new MailAddress(FromName); //发送者，要和邮件服务器的验证信息对应，不能随便更改
                myMail.To.Add(new MailAddress(ToMail)); //接收者
                myMail.Subject = "周游科技验证码"; //邮件标题
                myMail.SubjectEncoding = Encoding.UTF8; //标题编码
                myMail.Body = "您的验证码为：" + RanNum + " <br/> 验证码半小时内有效！"; //邮件内容
                myMail.BodyEncoding = Encoding.UTF8; //邮件内容编码
                myMail.IsBodyHtml = true;     //邮件内容是否支持html
                SmtpClient smtp = new SmtpClient(); //创建smtp实例对象
                smtp.Host = "smtp.qq.com"; //邮件服务器SMTP

                //SMTP端口，QQ邮箱填写587  
                smtp.Port = 587;
                //启用SSL加密  
                //smtp.EnableSsl = true;

                smtp.Credentials = new NetworkCredential(FromName, "aatrpsonjyzxbaja"); //邮件服务器验证信息
                smtp.Send(myMail); //发送邮件

                //记录验证码记录
                T_BASE_VERIFICATION tbv = new T_BASE_VERIFICATION();
                tbv.TBV_CODE = RanNum;
                tbv.TBV_MAIL = ToMail;
                tbv.TBV_SEND_DATE = DateTime.Now;
                BllT_BASE_VERIFICATION.InsertData(tbv);
            }
            catch (Exception ex)
            {
                RetMsg = ex.Message;
            }
            return RetMsg;
        }

        /// 发送Mail
        /// </summary>
        /// <param name="ToMail">接收人邮箱</param>
        /// <param name="Msg">邮箱内容</param>
        /// <returns>返回值非空时异常</returns>
        protected string SendMail(string ToMail, string Msg)
        {
            string RetMsg = "";
            string FromName = "694766804@qq.com";
            try
            {
                MailMessage myMail = new MailMessage(); //创建邮件实例对象
                myMail.From = new MailAddress(FromName); //发送者，要和邮件服务器的验证信息对应，不能随便更改
                myMail.To.Add(new MailAddress(ToMail)); //接收者
                myMail.Subject = "周游科技"; //邮件标题
                myMail.SubjectEncoding = Encoding.UTF8; //标题编码
                myMail.Body = Msg; //邮件内容
                myMail.BodyEncoding = Encoding.UTF8; //邮件内容编码
                myMail.IsBodyHtml = true;     //邮件内容是否支持html
                SmtpClient smtp = new SmtpClient(); //创建smtp实例对象
                smtp.Host = "smtp.qq.com"; //邮件服务器SMTP
                smtp.Credentials = new NetworkCredential(FromName, "hofergbknyvrbech"); //邮件服务器验证信息
                smtp.Send(myMail); //发送邮件
            }
            catch (Exception ex)
            {
                RetMsg = ex.Message;
            }
            return RetMsg;
        }
        #endregion

        #region 事务处理
        /// <summary>
        /// 启动事务
        /// </summary>
        protected void IBeginTransaction()
        {
            DalBase.IBeginTransaction();//启动事务
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        protected void ICommitTransaction()
        {
            DalBase.ICommitTransaction();//提交事务
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        protected void IRollBackTransaction()
        {
            DalBase.IRollBackTransaction();//回滚事务
        }
        #endregion

        #region Base64转图片

        protected string Base64Img(IHostingEnvironment hostingEnv, string base64Str, string PathStr, string imgName)
        {
            string imgPath = "";
            try
            {
                byte[] b = Convert.FromBase64String(base64Str.Split(',')[1]);

                if (!System.IO.Directory.Exists(hostingEnv.WebRootPath + PathStr))
                {
                    System.IO.Directory.CreateDirectory(hostingEnv.WebRootPath + PathStr);
                }

                imgPath = PathStr + imgName;
                string path = Path.Combine(hostingEnv.WebRootPath + imgPath);//实际情况需要根据base64判断文件后缀名
                System.IO.File.WriteAllBytes(path, b);

            }
            catch (Exception ex)
            {

            }
            return imgPath;
        }


        #endregion


    }
}